<template>
  <div class="carousel" :style="{ height: height }">
    <div class="carousel-container">
      <!-- 轮播图片 -->
      <div
        v-for="(item, index) in list"
        :key="index"
        class="carousel-image"
        :class="{ active: currentIndex === index }"
        :style="{ backgroundImage: `url(${getImageUrl(item)})` }"
      ></div>
      <!-- 指示器区域 -->
      <div v-if="showIndicators" class="indicators-container">
        <div
          v-for="(_, index) in list"
          :key="index"
          class="indicator-item"
          :class="{ active: currentIndex === index }"
          @click="setCurrentIndex(index)"
          @keydown.enter="setCurrentIndex(index)"
          @keydown.space="setCurrentIndex(index)"
          :tabindex="0"
          :aria-label="`切换到第${index + 1}张图片`"
          role="button"
        >
          <div class="indicator-bg">
            <div
              class="indicator-progress"
              :style="{ width: currentIndex === index ? `${progress}%` : '0%' }"
            ></div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { ref, onMounted, onUnmounted, watch } from "vue";
import { publicSrc } from "@/utils/common";

// 组件属性定义
interface Props {
  list: (string | Record<string, any>)[]; // 轮播数据数组，支持字符串数组或对象数组
  imageField?: string; // 当list为对象数组时，指定图片字段名
  height?: string; // 轮播图高度
  interval?: number; // 轮播间隔时间（毫秒）
  showIndicators?: boolean; // 是否显示指示器
  autoplay?: boolean; // 是否自动播放
  modelValue?: number; // v-model绑定的当前页索引
}

const props = withDefaults(defineProps<Props>(), {
  height: '100vh',
  interval: 3000,
  showIndicators: true,
  autoplay: true,
  modelValue: 0
});

// 定义emit
const emit = defineEmits<{
  'update:modelValue': [value: number],
  'change': [index: number]
}>();

// 响应式数据
const currentIndex = ref(props.modelValue);
const progress = ref(0);
const interval = ref<number | null>(null);
const progressInterval = ref<number | null>(null);

// 进度条更新频率（毫秒）
const PROGRESS_UPDATE_INTERVAL = 50;

// 获取图片URL的方法
const getImageUrl = (item: string | Record<string, any>): string => {
  if (typeof item === 'string') {
    return publicSrc(item);
  }
  
  if (props.imageField && item[props.imageField]) {
    return publicSrc(item[props.imageField]);
  }
  
  // 如果没有指定imageField或字段不存在，尝试常见的图片字段
  const commonImageFields = ['image', 'img', 'src', 'url', 'photo', 'picture'];
  for (const field of commonImageFields) {
    if (item[field]) {
      return publicSrc(item[field]);
    }
  }
  
  // 如果都没有找到，返回空字符串或默认图片
  return '';
};

// 开始轮播
const startCarousel = () => {
  if (!props.autoplay) return;
  
  interval.value = window.setInterval(() => {
    nextImage();
  }, props.interval);

  startProgress();
};

// 停止轮播
const stopCarousel = () => {
  if (interval.value) {
    clearInterval(interval.value);
    interval.value = null;
  }
  if (progressInterval.value) {
    clearInterval(progressInterval.value);
    progressInterval.value = null;
  }
};

// 开始进度条
const startProgress = () => {
  if (!props.autoplay) return;
  
  // 清除之前的进度条定时器
  if (progressInterval.value) {
    clearInterval(progressInterval.value);
    clearInterval(progressInterval.value);
    progressInterval.value = null;
  }

  // 重置主轮播定时器，确保进度条完成后再开始下一轮
  if (interval.value) {
    clearInterval(interval.value);
    interval.value = null;
  }

  progress.value = 0;
  progressInterval.value = window.setInterval(() => {
    progress.value += 100 / (props.interval / PROGRESS_UPDATE_INTERVAL);

    if (progress.value >= 100) {
      progress.value = 100;
      nextImage();
    }
  }, PROGRESS_UPDATE_INTERVAL);
};

// 下一张图片
const nextImage = () => {
  const newIndex = (currentIndex.value + 1) % props.list.length;
  setCurrentIndex(newIndex);
};

// 设置当前图片索引
const setCurrentIndex = (index: number) => {
  if (index === currentIndex.value) return;
  
  // 确保索引在有效范围内
  if (index < 0 || index >= props.list.length) {
    index = 0;
  }

  // 重置进度条
  progress.value = 0;
  currentIndex.value = index;
  
  // 触发v-model更新
  emit('update:modelValue', index);
  
  // 触发change事件，返回当前下标
  emit('change', index);

  // 重新开始进度条
  startProgress();
};

// 监听v-model值变化
watch(() => props.modelValue, (newValue) => {
  if (newValue !== currentIndex.value && newValue >= 0 && newValue < props.list.length) {
    setCurrentIndex(newValue);
  }
});

// 监听数据数组变化
watch(() => props.list, (newList) => {
  if (newList && newList.length > 0) {
    // 如果当前索引超出新数组范围，重置为0
    if (currentIndex.value >= newList.length) {
      currentIndex.value = 0;
      emit('update:modelValue', 0);
    }
    progress.value = 0;
    if (props.autoplay) {
      startCarousel();
    }
  }
}, { immediate: true });

onMounted(() => {
  if (props.autoplay) {
    startCarousel();
  }
});

onUnmounted(() => {
  stopCarousel();
});

// 暴露方法给父组件
defineExpose({
  nextImage,
  startCarousel,
  stopCarousel,
});
</script>

<style lang="scss" scoped>
.carousel {
  width: 100%;
  position: relative;
  overflow: hidden;
  background-color: #000;

  .carousel-container {
    position: relative;
    width: 100%;
    height: 100%;
  }

  .carousel-image {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background-size: cover;
    background-position: center;
    background-repeat: no-repeat;
    background-color: #021a32;
    opacity: 0;
    transform: scale(1.05);
    transition: opacity 0.8s ease-in-out, transform 0.8s ease-in-out;

    &.active {
      opacity: 1;
      transform: scale(1);
    }
  }

  .indicators-container {
    position: absolute;
    bottom: 50px;
    left: 50px;
    z-index: 20;
    display: flex;
    flex-direction: row;
    gap: 5px;
    align-items: center;

    .indicator-item {
      cursor: pointer;
      transition: all 0.3s ease;

      &:hover {
        transform: scale(1.1);

        .indicator-bg {
          background: rgba(255, 255, 255, 0.6);
        }
      }

      .indicator-bg {
        width: 16px;
        height: 10px;
        background: rgba(255, 255, 255, 0.3);
        border-radius: 2px;
        overflow: hidden;
        position: relative;
        transition: width 0.3s ease-in-out;

        clip-path: polygon(35% 0%, 100% 0%, 65% 100%, 0% 100%);

        .indicator-progress {
          height: 100%;
          background: rgba(42, 130, 228, 1);
          transition: width 0.05s linear;
          border-radius: 2px;
          box-shadow: 0 0 10px rgba(69, 128, 221, 0.5);
        }
      }

      &.active {
        .indicator-bg {
          width: 30px;
          background: rgba(255, 255, 255, 0.5);
          clip-path: polygon(20% 0%, 100% 0%, 80% 100%, 0% 100%);
          
          .indicator-progress {
            background: rgba(42, 130, 228, 1);
          }
        }

        // 添加脉冲动画效果
        animation: pulse 2s infinite;
      }
    }
  }
}

// 脉冲动画
@keyframes pulse {
  0% {
    transform: scale(1);
  }
  50% {
    transform: scale(1.05);
  }
  100% {
    transform: scale(1);
  }
}

// 响应式设计
@media (max-width: 768px) {
  .carousel {
    .indicators-container {
      bottom: 30px;
      left: 30px;

      .indicator-item {
        .indicator-bg {
          width: 16px;
          height: 10px;
        }

        &.active {
          .indicator-bg {
            width: 30px;
          }
        }
      }
    }
  }
}

@media (max-width: 480px) {
  .carousel {
    .indicators-container {
      bottom: 20px;
      left: 20px;
      gap: 5px;

      .indicator-item {
        .indicator-bg {
          width: 16px;
          height: 10px;
        }

        &.active {
          .indicator-bg {
            width: 30px;
          }
        }
      }
    }
  }
}
</style>